package lh.chatroom.controller;

import lh.chatroom.controller.support.AjaxResponse;
import lh.chatroom.controller.support.BaseController;
import lh.chatroom.domain.Member;
import lh.chatroom.form.MemberForm;
import lh.chatroom.service.IMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Optional;

/**
 * Created by lh on 2016/7/26.
 */
@Controller
public class MemberController extends BaseController {
    @Autowired
    private IMemberService memberService;

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse create(@RequestBody @Valid MemberForm form, BindingResult result) {
        if (result.hasErrors()) {
            return getErrorInfo(result);
        }
        Member member = form.asMember();
        memberService.create(member);
        return AjaxResponse.ok().msg("加入房间成功");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse update(@RequestBody @Valid MemberForm form, BindingResult result) {
        Optional<Member> memberOptional = memberService.getById(form.getId());
        if (!memberOptional.isPresent()) {
            return AjaxResponse.fail().msg("更新失败").detail("成员不存在");
        }
        Member member = form.asMember();
        memberService.update(member);
        return AjaxResponse.ok().msg("更新成功");
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResponse delete(@PathVariable String id) {
        Optional<Member> memberOptional = memberService.getById(id);
        if (!memberOptional.isPresent()) {
            return AjaxResponse.fail().msg("更新失败").detail("成员不存在");
        }
        memberService.delete(memberOptional.get());
        return AjaxResponse.ok().msg("删除成功");
    }
}
